<?php

namespace App\Exceptions;

use App\Models\StaticCode;

/**
 * 错误信息统一处理
 * Class Error
 * @package App\Exceptions
 */
class Error
{

    /** @var string default message */
    protected static $message = 'INVALID REQUEST';

    /**
     * get error message
     * @param $code
     * @return mixed|string
     */
    public static function getMessage($code)
    {
        try {
            $error = StaticCode::getInstance()->where('key', $code)->first();
            $message = $error ? $error->content : self::$message;
        } catch (\Exception $e) {
            $message = 'SYSTEM ERROR : ' . $e->getCode() . ' - ' . $e->getMessage();
        }
        return $message;
    }

    /**
     * handle error
     * @param $message
     * @param int $code
     * @return \Illuminate\Http\JsonResponse
     */
    public static function handle($message, $code = 9999)
    {
        $info = self::getMessage($code);
        $success = $code == 200 ? true : false;
        $format = [
            'message' => $success ? 'OK' : $info,
            'statusCode' => intval($code),
            'success' => $success,
            'result' => $message,
        ];
        return response()->json($format);
    }

}
